package cc.admin.modules.sys.controller;

import cc.admin.common.api.vo.Result;
import cc.admin.common.sys.api.ISysBaseAPI;
import cc.admin.common.sys.vo.LoginUser;
import cc.admin.common.util.CommonUtils;
import cc.admin.common.util.RestUtil;
import cc.admin.common.util.TokenUtils;
import cc.admin.common.util.oConvertUtils;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <getPageFilterFields>
 * 用户表 前端控制器
 * </getPageFilterFields>
 *
 * @Author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/common")
public class CommonController {

	@Autowired
	private ISysBaseAPI sysBaseAPI;

	@Value(value = "${cc.admin.path.upload}")
	private String uploadPath;

	/**
	 * 本地：local minio：minio 阿里：alioss
	 */
	@Value(value="${cc.admin.uploadType}")
	private String uploadType;

	private String fileSeparator = "/";

	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * @Author 政辉
	 * @return
	 */
	@GetMapping("/403")
	public Result<?> noauth()  {
		return Result.error("没有权限，请联系管理员授权");
	}

	@PostMapping("/quasarUpload")
	public Result<?> handleFileUpload(@RequestPart(value = "file") final MultipartFile multipartFile,HttpServletRequest request) throws IOException {
		Result<?> result = new Result<>();
		final byte[] bytes = multipartFile.getBytes();
		String ctxPath = uploadPath;
		String fileName = null;
		File file = new File(ctxPath);
		if (!file.exists()) {
			file.mkdirs();// 创建文件根目录
		}
		// 获取文件名
		String orgName = multipartFile.getOriginalFilename();
		orgName = CommonUtils.getFileName(orgName);
		if(orgName.indexOf(".")!=-1){
			fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
		}else{
			fileName = orgName+ "_" + System.currentTimeMillis();
		}
		String savePath = file.getPath() + fileSeparator + fileName;
		final Path path = Paths.get(savePath);
		Files.write(path, bytes);
		if(oConvertUtils.isNotEmpty(savePath)){
			result.setMessage(fileName);
			result.setSuccess(true);
		}else {
			result.setMessage("上传失败！");
			result.setSuccess(false);
		}
		return result;
	}
	/**
	 * 文件上传统一方法
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/upload")
	public Result<?> upload(HttpServletRequest request) {
		String savePath = "";
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		// 获取上传文件对象
		MultipartFile file = multipartRequest.getFile("file");
		savePath = this.staticUploadLocal(file);
		return oConvertUtils.isNotEmpty(savePath) ? Result.ok(savePath) : Result.error("上传失败！");
	}

	/**
	 * 动态本地文件上传
	 * @param mf 文件
	 * @return
	 */
	private String uploadLocal(MultipartFile mf){
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		try {
			String ctxPath = uploadPath;
			String fileName = null;
			String dateDir= new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
			File file = new File(ctxPath + fileSeparator + sysUser.getTenantId() + fileSeparator+dateDir+fileSeparator );
			if (!file.exists()) {
				file.mkdirs();// 创建文件根目录
			}
			// 获取文件名
			String orgName = mf.getOriginalFilename();
			orgName = CommonUtils.getFileName(orgName);
			if(orgName.indexOf(".")!=-1){
				fileName = IdUtil.fastUUID().replace("-", "") + orgName.substring(orgName.indexOf("."));
			}else{
				fileName = orgName+ "_" + System.currentTimeMillis();
			}
			String savePath = file.getPath() + fileSeparator + fileName;
			File saveFile = new File(savePath);
			FileCopyUtils.copy(mf.getBytes(), saveFile);
			return savePath;
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return "";
	}

	/**
	 * 本地文件上传
	 * @param mf 文件
	 * @return
	 */
	private String staticUploadLocal(MultipartFile mf){
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		try {
			String ctxPath = uploadPath;
			String fileName = null;
			String dateDir= new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
			String fileNamePath=fileSeparator + sysUser.getTenantId() + dateDir;
			File file = new File(ctxPath + fileNamePath);
			if (!file.exists()) {
				file.mkdirs();// 创建文件根目录
			}
			// 获取文件名
			String orgName = mf.getOriginalFilename();
			orgName = CommonUtils.getFileName(orgName);
			if(orgName.indexOf(".")!=-1){
				fileName = IdUtil.fastUUID().replace("-", "") + orgName.substring(orgName.indexOf("."));
			}else{
				fileName = orgName+ "_" + System.currentTimeMillis();
			}
			String savePath = file.getPath() + fileSeparator + fileName;
			File saveFile = new File(savePath);
			FileCopyUtils.copy(mf.getBytes(), saveFile);
			return fileNamePath+fileSeparator + fileName;
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}
		return "";
	}
	/**
	 * 预览图片&下载文件
	 * 请求地址：http://localhost:8080/common/static/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
	 *
	 * @param request
	 * @param response
	 */
	@GetMapping(value = "/static/**")
	public void view(HttpServletRequest request, HttpServletResponse response) {
		// ISO-8859-1 ==> UTF-8 进行编码转换
		String imgPath = extractPathFromPattern(request);
		if(oConvertUtils.isEmpty(imgPath) || imgPath=="null"){
			return;
		}
		// 其余处理略
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			imgPath = imgPath.replace("..", "");
			if (imgPath.endsWith(",")) {
				imgPath = imgPath.substring(0, imgPath.length() - 1);
			}
			String filePath = uploadPath + fileSeparator + imgPath;
			File file = new File(filePath);
			if(!file.exists()){
				response.setStatus(404);
				log.info("文件[{}]不存在..",filePath);
				return;
			}
			// 设置强制下载不打开
			response.setContentType("application/force-download");
			response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
			inputStream = new BufferedInputStream(new FileInputStream(filePath));
			outputStream = response.getOutputStream();
			IoUtil.copy(inputStream, outputStream);
			response.flushBuffer();
		} catch (IOException e) {
			log.error("预览文件失败" + e.getMessage());
			response.setStatus(404);
			e.printStackTrace();
		} finally {
			IoUtil.close(inputStream);
			IoUtil.close(outputStream);
		}

	}
	@GetMapping(value = "/dynView/{id}")
	public void dynView(@PathVariable("id") String id,HttpServletRequest request,HttpServletResponse response){
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			String relativePath = jdbcTemplate.queryForObject(String.format("select relative_path from dyn_file where id='%s'", id),String.class);
			if (relativePath!=null){
				File file = new File(relativePath);
				if(!file.exists()){
					response.setStatus(404);
					System.out.println("文件不存在:"+relativePath);
					return ;
				}
				// 设置强制下载不打开
				response.setContentType("application/force-download");
				response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
				inputStream = new BufferedInputStream(new FileInputStream(relativePath));
				outputStream = response.getOutputStream();
				IoUtil.copy(inputStream, outputStream);
				response.flushBuffer();
			}

		}catch (IOException e){
			log.error("预览文件失败" + e.getMessage());
			response.setStatus(404);
			e.printStackTrace();
		}finally {
			IoUtil.close(inputStream);
			IoUtil.close(outputStream);
		}

	}

	/**
	 * 下载文件
	 * 请求地址：http://localhost:8080/common/download/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@GetMapping(value = "/download/**")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// ISO-8859-1 ==> UTF-8 进行编码转换
		String filePath = extractPathFromPattern(request);
		// 其余处理略
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			filePath = filePath.replace("..", "");
			if (filePath.endsWith(",")) {
				filePath = filePath.substring(0, filePath.length() - 1);
			}
			String localPath = uploadPath;
			String downloadFilePath = localPath + fileSeparator + filePath;
			File file = new File(downloadFilePath);
	         if (file.exists()) {
				 // 设置强制下载不打开  
	         	response.setContentType("application/force-download");
	 			response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
	 			inputStream = new BufferedInputStream(new FileInputStream(file));
	 			outputStream = response.getOutputStream();
	 			byte[] buf = new byte[1024];
	 			int len;
	 			while ((len = inputStream.read(buf)) > 0) {
	 				outputStream.write(buf, 0, len);
	 			}
	 			response.flushBuffer();
	         }

		} catch (Exception getUuid) {
			log.info("文件下载失败" + getUuid.getMessage());
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException getUuid) {
					getUuid.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException getUuid) {
					getUuid.printStackTrace();
				}
			}
		}

	}

	/**
	 * @功能：pdf预览Iframe
	 * @param modelAndView
	 * @return
	 */
	@RequestMapping("/pdf/pdfPreviewIframe")
	public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
		modelAndView.setViewName("pdfPreviewIframe");
		return modelAndView;
	}

	/**
	  *  把指定URL后的字符串全部截断当成参数
	  *  这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
	 * @param request
	 * @return
	 */
	private static String extractPathFromPattern(final HttpServletRequest request) {
		String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
		String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
		return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
	}

    /**
     * 中转HTTP请求，解决跨域问题
     *
     * @param url 必填：请求地址
     * @return
     */
    @RequestMapping("/transitRESTful")
    public Result transitRESTful(@RequestParam("url") String url, HttpServletRequest request) {
        try {
            ServletServerHttpRequest httpRequest = new ServletServerHttpRequest(request);
            // 中转请求method、body
            HttpMethod method = httpRequest.getMethod();
            JSONObject params;
            try {
                params = JSON.parseObject(JSON.toJSONString(httpRequest.getBody()));
            } catch (Exception e) {
                params = new JSONObject();
            }
            // 中转请求问号参数
            JSONObject variables = JSON.parseObject(JSON.toJSONString(request.getParameterMap()));
            variables.remove("url");
            // 在 headers 里传递Token
            String token = TokenUtils.getTokenByRequest(request);
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", token);
            // 发送请求
            String httpURL = URLDecoder.decode(url, "UTF-8");
            ResponseEntity<String> response = RestUtil.request(httpURL, method, headers , variables, params, String.class);
            // 封装返回结果
            Result<Object> result = new Result<>();
            int statusCode = response.getStatusCodeValue();
            result.setCode(statusCode);
            result.setSuccess(statusCode == 200);
            String responseBody = response.getBody();
            try {
                // 尝试将返回结果转为JSON
                Object json = JSON.parse(responseBody);
                result.setResult(json);
            } catch (Exception e) {
                // 转成JSON失败，直接返回原始数据
                result.setResult(responseBody);
            }
            return result;
        } catch (Exception e) {
            log.debug("中转HTTP请求失败", e);
            return Result.error(e.getMessage());
        }
    }

}
